/**
 * Created by xiaoz on 16/8/13.
 */
define(["utils","base"],function(utils,baseClass){

  var TableCell = function(config){


    config.tagName = "td";

    TableCell.baseConstructor.call(this,config);

    this.initLayout(this.datasource,null,this.parent);


  }


  utils.extendClass(TableCell,baseClass);


  TableCell.prototype.setDisabled = function(disabled){
    this.disabled = disabled;
    for(var key in this.components){
      this.components[key].setDisabled(this.disabled);
    }
  };

  var TableRow = function(config){
    var _this = this;

    config.tagName = "TR";
    this.index = config.index;
    TableRow.baseConstructor.call(this,config);
    this.table = config.table;
    this.components=[];
    this.componentsInitActions = {};
    this.componentsInitActionsArray = {};
    this.group = config.group;

    this.datasource = config.datasource;
    this.pageview = config.pageview;
    this.disabledClassName = this.table.config.rowDisabledClassName;
    this.selectedMode = this.table.config.selectedMode;
    this.disabledColumns = this.table.config.disabledColumns;

    var colConfig = this.table.config.columns;
    for(var i=0,j=colConfig.length;i<j;i++){
      var c = colConfig[i];
      var cell = new TableCell({
        type:"tablecell",
        $$parent:this,
        $$pageview:config.pageview,
        $$datasource:this.datasource,
        table:this.table,
        root:c.cell,
        style:c.cellStyle
      });
      this.components.push(cell);
      this.$el.append(cell.$el);
    }

    var method_name =  this.table.config.comKey+"_rowclick";
    var method = this.pageview.plugin[method_name];
    this.$el.bind("click",function(e){
      method && method.call(_this.pageview.plugin,_this,{e:e});
    });

    var selectChangeMethodName =  this.table.config.comKey+"_selectchange";
    this.selectChangeMethod = this.pageview.plugin[selectChangeMethodName];

  }
  utils.extendClass(TableRow,baseClass);
  TableRow.prototype.remove = function(){
    if(this.group){
        var index = this.group.rows.indexOf(this);
        this.group.rows.splice(index,1);
        if(this.group.rows.length === 0){
          this.group.$el.addClass("displaynone");
        }
    }else{
        var index = this.table.rows.indexOf(this);
        this.table.rows.splice(index,1);
    }


    var indexInSelectedRows = this.table.selectedRows.indexOf(this);
    if(indexInSelectedRows>=0){
      this.table.selectedRows.splice(indexInSelectedRows,1);
    }
    this.$el.remove();

    if(this.table.getRowCount()===0){
      this.table.showNodata(true);
    }
  };

    TableRow.prototype.delegate = function (com_key, action) {
      var com_instance = this.refs[com_key];
      if (com_instance) {
          action(com_instance);
      } else {
          if (!this.config.components[com_key].ref) {
              console.log("请务必在" + com_key + "控件上设置ref:true");
          }
          this.componentsInitActions[com_key] = action;
      }
    };

    TableRow.prototype.delegates = function (com_key, action) {
        var com_instance = this.refs[com_key];
        if (com_instance) {
            action(com_instance);
        } else {
            if (!this.config.components[com_key].ref) {
                console.log("请务必在" + com_key + "控件上设置ref:true");
            }
            if(!this.componentsInitActionsArray[com_key]){
                this.componentsInitActionsArray[com_key] = [];
            }
            this.componentsInitActionsArray[com_key].push(action);
        }
    };

  TableRow.prototype.rebind = function(data){
    this.$el.empty();
    this.datasource = data;
    this.components=[];
    var colConfig = this.table.config.columns;
    for(var i=0,j=colConfig.length;i<j;i++){
      var c = colConfig[i];
      var cell = new TableCell({
        type:"tablecell",
        $$parent:this,
        $$pageview:this.config.pageview,
        $$datasource:this.datasource,
        table:this.table,
        root:c.cell,
        style:c.cellStyle
      });
      this.components.push(cell);
      this.$el.append(cell.$el);
    }
  };
  TableRow.prototype.selected = function(isFromParent){
    if(this.disabled){
      return;
    }
    if(isFromParent){
      if(this.config.disableParentSelect){
        return;
      }
    }
    this.isSelected = true;
    for(var i=0,j=this.components.length;i<j;i++){
      this.components[i].selected(true);
    }
  };

  TableRow.prototype.select = function(){
    if(this.disabled){
      return;
    }
    if(this.selectedMode==="m"){
      var index = this.table.selectedRows.indexOf(this);
      if(index>=0){
        this.table.selectedRows.splice(index,1);
        this.unSelected();
      }else{
        this.table.selectedRows.push(this);
       this.selected();
      }
    }else{
      var beforeSelectedRow = this.table.selectedRows[0];
      beforeSelectedRow&&beforeSelectedRow.unSelected();
      this.table.selectedRows[0] = this;
      this.selected();
    }


    this.selectChangeMethod && this.selectChangeMethod.call(this.pageview.plugin,this.table,{});

  };
    TableRow.prototype.unSelected = function(isFromParent){
      if(this.disabled){
        return;
      }
      if(isFromParent){
        if(this.config.disableParentSelect){
          return;
        }
      }
      this.isSelected = false;

      for(var i=0,j=this.components.length;i<j;i++){
        this.components[i].unSelected(true);
      }
    };

    TableRow.prototype.setDisabled = function(disabled){
      this.disabled = disabled;
      if(this.disabledClassName){
        if(this.disabled){
          this.$el.addClass(this.disabledClassName);
        }else{
          this.$el.remove(this.disabledClassName);
        }
      }

      for(var i=0,j=this.components.length;i<j;i++){
        if(this.disabledColumns){
          if(this.disabledColumns.indexOf(i)>=0){
            this.components[i].setDisabled(disabled);
          }
        }else{
          this.components[i].setDisabled(disabled);
        }
      }
    };


    var ListGroupHeader = function(config){
        var  _this = this;
        config.tagName = "TR";
        this.TD = $("<td></td>");
        this.$$childrenWrapper = this.TD;
        ListGroupHeader.baseConstructor.call(this,config);
        this.TD.attr("colspan",this.config.table.config.columns.length);

        this.$el.append(this.TD);
        var isCanCollapse = config.isCanCollapse;
        var className = "yy-sticky displayflex";

        if(isCanCollapse===true){
          this.isCollapse = false;
          className += " yy-icommon yy-listgroup-colheader";

          this.$el.bind("click",function(){

            if(_this.isCollapse){
              _this.parent.expand();
              _this.isCollapse = false;
              _this.$el.removeClass("yy-listgroup-header-collapse");
            }else{
              _this.isCollapse = true;
              _this.parent.collapse();
              _this.$el.addClass("yy-listgroup-header-collapse");
            }
          })
        }
        this.$el.addClass(className);
        //
        this.initLayout(config.$$datasource,null,null);
      }

      utils.extendClass(ListGroupHeader,baseClass);

    ListGroupHeader.prototype.remove = function(){
      this.$el.remove();
    }

    var ListGroup = function(config){
      config.tagName = "TBODY";
      this.table = config.table;
      ListGroup.baseConstructor.call(this,config);
      var isCanCollapse = this.parent.config.isCanCollapse;
      this.componentsInitActions = {};

      this.$el.attr("data-gval",config.groupValue);
      this.groupHeader = new ListGroupHeader({
        $$datasource:config.groupHeaderData,
        type:"listgroupheader",
        isCanCollapse:isCanCollapse,
        table:this.table,
        root:this.config.rootConfig.groupHeader,
        style:this.config.rootConfig.groupHeaderStyle,
        $$pageview:this.pageview,
        groupValue:config.groupValue,
        $$parent:this,
      });
       this.display = "block";
      this.groupValue = config.groupValue;
      this.$el.append(this.groupHeader.$el);
      this.rows = [];
    }

    utils.extendClass(ListGroup,baseClass);

    ListGroup.prototype.expand = function(){
        //列表展开
        this.$el.removeClass("yy-list-collapse");
      // this.groupBodyInner.removeClass("displaynone");
    };
    ListGroup.prototype.collapse = function(){
        //列表收起
        this.$el.addClass("yy-list-collapse");
      // this.groupBodyInner.addClass("displaynone");
    };

    ListGroup.prototype.insertRow = function(newRow,index){
      this.show();
      var row = this.rows[index];
      this.$el.removeClass("displaynone");
      if(row){
          newRow.$el.insertBefore(row.$el);
          this.rows.splice(index,0,newRow);
        }else{
          this.rows.push(newRow);
          this.$el.append(newRow.$el);
        }
        window.setTimeout(function(){
          newRow.$el[0].scrollIntoView();
       },100);
      return newRow;
    };
    ListGroup.prototype.append=function(row){
      this.show();
      this.$el.append(row);
    };
    ListGroup.prototype.show=function(){
      if( this.display == "block"){
        return;
      }
      if(this.display=="none"){
        this.$el.removeClass("displaynone");
         this.display = "block";
      }

    };
    ListGroup.prototype.remove = function(){
      if(this.parent.groups[this.groupValue]){
        delete this.parent.groups[this.groupValue];
      }
      this.$el.remove();
      this.groupHeader.remove();
    }




    var Component = function(config){
        var _this = this;
        Component.baseConstructor.call(this,config);

        this.isStatic = config.isStatic || false;
        if(!this.isStatic){
          this.initAjaxConfig(config.ajaxConfig);
        }
        this.rows = [];

        this.groupKey = this.config.groupKey;
        this.isGroupList = this.groupKey!=null;
        this.groups = {};

        var className = "yy-table-wrapper";
        this.table = $("<table class='yy-table'></table>");
        this.$el.addClass(className);
        this.selectedRows = [];
        this._createHeader();
        var pluginParseDataMethodName = this.config.comKey+"_parsedata";
        this.pluginParseDataMethod = this.pageview.plugin[pluginParseDataMethodName];
        if(!this.pluginParseDataMethod){
          console.error("程序错误：没有定义"+_this.config.comKey+
          "_parsedata 需要在parsedata中处理params中的data对象然后将数组以及总条数返回{data:[],sumCount:0} 不分页的话sumCount为0");
        }
        var pluginBeforeLoadDataMethodName = this.config.comKey+"_beforeload";
        this.pluginBeforeLoadDataMethod = this.pageview.plugin[pluginBeforeLoadDataMethodName];
        var pluginAfterLoadDataMethodName = this.config.comKey+"_afterload";
        this.pluginAfterLoadDataMethod = this.pageview.plugin[pluginAfterLoadDataMethodName];
        this.$el.append(this.table);



        var pluginAfterBindMethodName = this.config.comKey+"_afterbinddata";
        this.pluginAfterBindMethod = this.pageview.plugin[pluginAfterBindMethodName];


        if(this.config.nodata){
         this.getComponentInstanceByComKey(this.config.nodata,null,null,function(comInstance){
           _this.$el.append(comInstance.$el);
           comInstance.$el.addClass("displaynone");
           _this.noDataDom= comInstance;
       },
       function(){});
     }
    }

    utils.extendClass(Component,baseClass);

    Component.prototype.appendRow = function(rowData){
      this.insertRow(rowData,this.rows.length+1);
    };


    Component.prototype.getRowCount = function(){
      if(this.isGroupList){
        var len = 0;
        this.eachRow(function(row){
          len+=1;
        });
        return len;
      }else{
        return this.rows.length;
      }
   };


      Component.prototype.insertGroup = function(rowdata,index){
      if(!this.isGroupList){
        return this;
      }
       var groupValue = rowdata[this.groupKey];
        var group = this.groups[groupValue];
        if(group){
          return this;
        }
      group = new ListGroup({
            type:"listgroup",
            rootConfig:this.config,
            table:this,
            style:this.config.groupStyle,
            $$pageview:this.pageview,
            groupValue:groupValue,
            groupHeaderData:rowdata,
            $$rowInstance:null,
            $$parent:this,
          });
      this.groups[groupValue] = group;
      var nextgroup = this.getGroupByIndex(index);
      if(nextgroup){
        group.$el.insertBefore(nextgroup.$el);
      }else{
        this.table.append(group.$el);
      }

      return this;
    }

     Component.prototype.getGroupByIndex = function(index){
      var groupDoms = this.$el.children();
      var groupDom = groupDoms[index];
      var group;
      if(groupDom){
        var groupValue = groupDom.getAttribute("data-gval");
        group = this.groups[groupValue];
      }
      return group;
    };


    Component.prototype.insertRow = function(rowData,index){
      var newRow = new TableRow({
        table:this,
        datasource:rowData,
        style:this.config.rowStyle,
        pageview:this.pageview
      });
      if(this.isGroupList){
        var groupValue = rowData[this.groupKey];
        var group = this.groups[groupValue];
        if(group){
          var row = this.createGroupListRow(rowData,group);
          this.showNodata(false);
          return group.insertRow(row,index);
        }else{
            this.insertGroup(rowData,0);
            this.insertRow(rowData,index)
            return;
        }
        return;
      }


      this.showNodata(false);

      var row = this.rows[index];
      if(row){
          newRow.$el.insertBefore(row.$el);
          this.rows.splice(index,0,newRow);
        }else{
          this.rows.push(newRow);
          this.TBody.append(newRow.$el);
        }
       //  window.setTimeout(function(){
       //    newRow.$el[0].scrollIntoView();
       // },100);
    };

    Component.prototype.showNodata = function(showOrHide){
      var _this = this;
      if(this.noDataDom){
        if(showOrHide){
          if(this.parent){
            this.parent.canLoadMore = false;
            this.parent.hideLoadMore&&this.parent.hideLoadMore();
          }
          this.noDataDom.$el.removeClass("displaynone");
        }else{
          this.noDataDom.$el.addClass("displaynone");
        }
      }
    };

    Component.prototype.loadPageDataByIndex = function(pageIndex){
      var _this = this;
      if(isNaN(pageIndex)){
        console.error("loadPageDataByIndex 传参数必须是数字");
      }
      pageIndex = parseInt(pageIndex);
      this.ajaxConfig.data[this.pageNumKey]=pageIndex;
      this.loadData();
    };

    Component.prototype.getCurPageIndex = function(){
      return this.ajaxConfig.data[this.pageNumKey];

    };

    Component.prototype.selectAll = function(){
      var _this = this;
      if(this.config.selectedMode==="m"){
        this.selectedRows = [];
        this.eachRow(function(row){
          if(!row.disabled){
            _this.selectedRows.push(row);
            row.selected();
          }

        });
      }
    };

    Component.prototype.eachRow = function(callback){
     if(this.isGroupList){
       for(var key in this.groups){
         var group = this.groups[key];
         for(var i=0,j=group.rows.length;i<j;i++){
           callback(group.rows[i],i,group);
         }
       }
     }else{
       for(var i=0,j=this.rows.length;i<j;i++){
         callback(this.rows[i],i);
       }
     }
   };

    Component.prototype.clearSelectAll = function(){
      var _this = this;
      if(this.config.selectedMode==="m"){
        this.selectedRows = [];
        this.eachRow(function(row){
          row.unSelected();
        });
      }
    };

    Component.prototype.setAjaxConfigParams = function(obj,type){
      this.ajaxConfig = this.config.ajaxConfig||{};
      if(type === "reset"){                         //需要将数据重新刷新
         this.ajaxConfig.data = {};
      }else{
          this.ajaxConfig.data = this.config.ajaxConfig.data ||{};
      }
      for(var key in obj){
        this.ajaxConfig.data[key] = obj[key];
      }

    };

    Component.prototype.deleteAjaxConfigParams = function(obj){
      this.ajaxConfig = this.config.ajaxConfig||{};
      this.ajaxConfig.data = this.config.ajaxConfig.data ||{};
      for(var key in obj){
        delete this.ajaxConfig.data[key];
      }
    };


    Component.prototype.reload = function(){
      this.ajaxConfig = this.beforeAjaxConfig;
      if(this.isPullLoad ===true){
        this.parent&&this.parent.setCanLoadMore({isReload:true});
        if(this.isFirstLoad){
          this.loadFirstPageData();
        }else{
          this.loadNextPageData();
        }
      }else{
        this.loadData();
      }
    };

    Component.prototype.loadNextPageData  = function(){
      this.isFirstLoad = false;
      var curPageIndex = this.getCurPageIndex()||0;
      if(isNaN(curPageIndex)){
        curPageIndex = 0;
      }
      curPageIndex = parseInt(curPageIndex)+1;
      this.ajaxConfig.data[this.pageNumKey]=curPageIndex;
      this.pullLoadData();
    };

    Component.prototype.loadFirstPageData = function(params){
      this.empty();
      this.isPullLoad = true;
      params=params||{};
      var _this = this;
      this.parentAnimate = params.parentAnimate;
      if(params.parentAnimate === false&& _this.parent){
        window.setTimeout(function(){
          _this.parent.hideLoadMore()
        },100);

      }else{
        // _this.parent&& _this.parent.setCanLoadMore();
      }
      this.isFirstLoad = true;
      this.ajaxConfig.data[this.pageNumKey]=1;
      window.setTimeout(function(){
        if(_this.parent){
          _this.parent.setCanLoadMore();
        }
        _this.pullLoadData({isFirstLoad:true});
      },200);
    };

    Component.prototype.groupBy = function(groupKey,isPaginat){
      this.empty();
      var _this = this;
      if(groupKey){
        this.groupKey = groupKey;
        this.isGroupList = true;
        this.groups = {};
      }else{
        this.isGroupList = false;
        this.groupKey = null;
        this.groups = {};
      }
      if(isPaginat){
        if(_this.parent&&_this.parent.setCanLoadMore){
            _this.parent.setCanLoadMore();
        }
        _this.loadFirstPageData();
      }else{
        _this.loadPageDataByIndex(1);
      }

    };

    Component.prototype.pullLoadData = function(config){
      config = config||{};
      var timeout = this.ajaxConfig.timeout || 7000;
      var loadingTimeout = timeout+1000;
      var _this = this;
      this.showNodata(false);
      var params = this.ajaxConfig.data||{};
      if(this.parent){
        this.parent.canLoadMore = false;
      }

      this.beforeAjaxConfig = utils.copy(this.ajaxConfig);
      utils.ajax({
            type:this.ajaxConfig.type||'get',
            url:this.ajaxConfig.url,
            pageviewInstance:this.pageview,
            timeout:timeout,
            data:params,
            success:function(data){
              var DataInfo = _this.pluginParseDataMethod.call(_this.pageview.plugin,_this,{params:params,data:data});
              var ArrData = DataInfo.data;

              if(DataInfo === false){
                _this.setLoadMoreError();
                return;
              }
              if(DataInfo === undefined||ArrData===undefined){
                console.error("程序错误："+_this.config.comKey+"_parsedata 方法没有返回值或者返回值错误 返回值格式：{data:[],sumCount:0}");
              }



              if(!(ArrData instanceof Array)){
                console.error(_this.config.comKey+"返回的数据不是数组类型,或者在"
                  +_this.config.comKey+"_parsedata方法中进行预处理 返回值格式：{data:[],sumCount:0}");
              }

              _this.bindData(ArrData,config);
          },
            error:function(err){
              _this.setLoadMoreError({});
            }
      })

    };

    Component.prototype.setLoadMoreLoadStateWhenBindDone = function(datasource,isFirstLoad){
     var _this = this;
     if(this.getRowCount()===0){
       this.parent && this.parent.hideLoadMore();
       return;
     }

        if(datasource.length<_this.ajaxConfig.pageSize){

           _this.parent.setHasLoadDone&&_this.parent.setHasLoadDone();
       }else{
        if(isFirstLoad&&this.parentAnimate===false){
        }else{
          _this.parent.setCanLoadMore&&_this.parent.setCanLoadMore();
        }
       }
   },

    Component.prototype.setLoadMoreError = function(para){
      var _this = this;
      _this.parent.setLoadMoreErrorState&&_this.parent.setLoadMoreErrorState();
      _this.ajaxConfig = _this.beforeAjaxConfig;
      _this.pluginAfterLoadDataMethod&&_this.pluginAfterLoadDataMethod.call(_this.pageview.plugin,_this,{isSuccess:false});
    }


     Component.prototype.setLoadStateWhenBindDone = function(datasource){
      var _this = this;
      if(datasource.length<_this.ajaxConfig.pageSize){
          _this.parent.setHasLoadDone&&_this.parent.setHasLoadDone();
        }else{
          _this.parent.setCanLoadMore&&_this.parent.setCanLoadMore();
        }
    },




    Component.prototype.loadData = function(){
      params = params||{};
      var timeout = this.ajaxConfig.timeout || 7000;
      var loadingTimeout = timeout+1000;
      var _this = this;
      this.showNodata(false);
      var params = this.ajaxConfig.data||{};
      this.beforeAjaxConfig = utils.copy(this.ajaxConfig);
      this.empty();
      this.showLoading({
        timeout:loadingTimeout,
        loadingColor:this.config.loadingColor,
        style:{
          top:40
        },
        text:"正在加载,请耐心等待...",
        reloadCallback:function(){
          _this.ajaxConfig = _this.beforeAjaxConfig;
          _this.loadData();
        }
      });
      utils.ajax({
            type:this.ajaxConfig.type||'get',
            url:this.ajaxConfig.url,
            pageviewInstance:this.pageview,
            timeout:timeout,
            data:params,
            success:function(data){
              var DataInfo = _this.pluginParseDataMethod.call(_this.pageview.plugin,_this,{params:params,data:data});
              var ArrData = DataInfo.data;

              if(DataInfo === false){
                _this.setError(params);
                return;
              }
              if(DataInfo === undefined||ArrData===undefined){
                console.error("程序错误："+_this.config.comKey+"_parsedata 方法没有返回值或者返回值错误 返回值格式：{data:[],sumCount:0}");
              }



              if(!(ArrData instanceof Array)){
                console.error(_this.config.comKey+"返回的数据不是数组类型,或者在"
                  +_this.config.comKey+"_parsedata方法中进行预处理 返回值格式：{data:[],sumCount:0}");
              }

              _this.bindData(ArrData);
              _this.pluginAfterLoadDataMethod&&_this.pluginAfterLoadDataMethod.call(_this.pageview.plugin,_this,{params:params,data:data});



              if(_this.config.paginator){
                var sumCount = DataInfo.sumCount;
                  var pageCount1 = DataInfo.pageCount;
                if(sumCount===null||sumCount===undefined||isNaN(sumCount)){
                  if(pageCount1===null||pageCount1===undefined||isNaN(pageCount1)) {
                      console.error(_this.config.comKey+"_parsedata  方法 中params中找到总条数返回，返回值格式：{data:[],sumCount:0} or {data:[],pageCount:0");
                  }
                }
                _this.pageview.delegate(_this.config.paginator,function(target){
                  if(sumCount===0){
                    target.$el.css({"display":"none"})
                    return;
                  }else{
                    target.$el.css({"display":"block"})
                  }
                  var curPageIndex = _this.getCurPageIndex();
                  target.bindChange(function(pageIndex){
                    _this.loadPageDataByIndex(pageIndex);
                  });
                    var pageCount;
                    if(pageCount1!==null&&pageCount1!==undefined&&!isNaN(pageCount1)) {
                        pageCount = pageCount1;
                    }
                    else{
                         pageCount = parseInt(Math.ceil(sumCount/_this.ajaxConfig.pageSize));

                    }
                  target.go(curPageIndex,pageCount);
                });
              }
              _this.hideLoading(true);

            },
            error:function(err){
              _this.setError();
            }
      })

    };





    Component.prototype.setError = function(){
      var _this = this;
      this.ajaxConfig = this.beforeAjaxConfig;
      this.hideLoading(false);
      this.pluginAfterLoadDataMethod&&this.pluginAfterLoadDataMethod.call(this.pageview.plugin,this,{data:[],isSuccess:false});


      if(_this.config.paginator){
        _this.pageview.delegate(_this.config.paginator,function(target){
          target.$el.css({"display":"none"})
        });
      }
    }


    Component.prototype.empty = function(){
      this.TBody&&this.TBody.empty();
      this.rows = [];
      for(var key in this.groups){
        this.groups[key].remove();
      }
      this.groups = {};
    };

    Component.prototype.bindGroupListData = function(datasource,isFirstLoad){
      //this.groupKey
      var _this = this;
      //this.groups
      var rowFragmentDict = {};
      var newGroups = {};
      for(var i=0,j=datasource.length;i<j;i++){
        var rowdata = datasource[i];
        var groupValue = rowdata[this.groupKey];
        if(!groupValue){
            rowdata[this.groupKey] = this.config.otherGroupName||"其他";
            groupValue =  this.config.otherGroupName||"其他";
        }
        if(!rowFragmentDict[groupValue]){
          rowFragmentDict[groupValue] = document.createDocumentFragment();
        }
        if(!this.groups[groupValue]){

          this.groups[groupValue] = new ListGroup({
            type:"listgroup",
            rootConfig:this.config,
            table:this,
            style:this.config.groupStyle,
            $$pageview:this.pageview,
            groupValue:groupValue,
            groupHeaderData:rowdata,
            $$rowInstance:null,
            $$parent:this,
          });
          newGroups[groupValue] = this.groups[groupValue];
        }

        var listRow = this.createGroupListRow(rowdata,this.groups[groupValue]);
        rowFragmentDict[groupValue].appendChild(listRow.$el[0]);
        this.groups[groupValue].rows.push(listRow);
      }



      for(var groupValue in rowFragmentDict){
        _this.groups[groupValue].append(rowFragmentDict[groupValue]);
        if(newGroups[groupValue]){
          _this.table.append(newGroups[groupValue].$el);
        }
      }
        _this.setLoadStateWhenBindDone(datasource,isFirstLoad);
        _this.pluginAfterLoadDataMethod&&_this.pluginAfterLoadDataMethod.call(_this.pageview.plugin,_this,{params:params,data:datasource});

    };

    Component.prototype.createGroupListRow = function(rowdata,listgroup){
      var row_instance = new TableRow({
        table:this,

          group:listgroup,
        datasource:rowdata,
        style:this.config.rowStyle,
        pageview:this.pageview
      });
      return row_instance;
    };


    Component.prototype.bindData =  function(data,config){

      var _this = this;
      if(this.isGroupList){
        this.bindGroupListData(data);
          if(this.getRowCount()===0){
              this.showNodata(true);
          }
        return;
      }
      var Fragment = document.createDocumentFragment();
    if(this.isPullLoad ===true){

    }else{
        this.empty();
    }
      for(var i=0,j=data.length;i<j;i++){
        var row = new TableRow({
          table:this,
          index:i,
          datasource:data[i],
          style:this.config.rowStyle,
          pageview:this.pageview
        });
        row.$el.appendTo(Fragment);
        this.rows.push(row);
      }
      if(this.getRowCount()===0){
        this.showNodata(true);
      }
      if(this.pluginAfterBindMethod){
          this.pluginAfterBindMethod.call(this.pageview.plugin,this,{});
      }

      window.setTimeout(function(){
        _this.TBody.append(Fragment);
        if(_this.isPullLoad===true){
          _this.setLoadMoreLoadStateWhenBindDone(data,config.isFirstLoad);
          _this.pluginAfterLoadDataMethod&&_this.pluginAfterLoadDataMethod.call(_this.pageview.plugin,_this,{params:params,data:data});
        }
      },30);


    };



    Component.prototype.initAjaxConfig = function(ajaxConfig){
      ajaxConfig = ajaxConfig||{};
      if(!ajaxConfig){
        console.warn("Table未配置ajaxConfig属性");
      }
      this.pageNumKey = ajaxConfig.pageNumKey;
      if(!this.pageNumKey){
        console.warn("Table 配置没有设置页码字段属性pageNumKey");
      }
      if(!ajaxConfig.pageSize){
        console.warn("Table ajaxConfig配置需要指定pageSize属性");
      }
      if(isNaN(ajaxConfig.pageSize)){
        console.warn("Table ajaxConfig配置需要指定pageSize属性为number类型");
      }
      ajaxConfig.pageSize = parseInt(ajaxConfig.pageSize);
      this.ajaxConfig = ajaxConfig;
    };


    Component.prototype.createHeader=function(columns){
      this.config.columns = columns;
      this.theader.empty();

      var theaderStyle = this.config.headerStyle;
      if(theaderStyle){
        this.theader.css(theaderStyle);
      }
      for(var i=0,j=columns.length;i<j;i++){



        var th = $("<th></th>");
        var colConfig = columns[i];
        var headerText = colConfig.headerText||"";
        var headerConfig = colConfig.header;
        if(headerConfig){


          (function(_th,_headerConfig,me){
            me.getComponentInstanceByComKey(_headerConfig,null,null,function(comInstance){
              _th.append(comInstance.$el);
            },
            function(){});
          })(th,headerConfig,this);

        }else{
          th.html(headerText);
        }

        var headerStyle = colConfig.headerStyle;
        if(headerStyle){
          th.css(headerStyle);
        }
        this.theader.append(th);
      }
    };

    Component.prototype._createHeader = function(){
      var columns = this.config.columns||[];
      if(!(columns instanceof Array)){
        console.log("table的columns属性必须为数组");
      }
      this.theader = $("<tr class='yy-table-header'></tr>");
      this.createHeader(columns);
      this.TBody = $("<tbody class='yy-table-content'></tbody>");

      this.table.append(this.theader).append(this.TBody);
    };

    return Component;
});
